package com.xuan.utils;


import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.xuan.constants.CommonConstants.CAPTCHA_PREFIX;


@Component
@Slf4j(topic = "CaptchaUtil")
public class CaptchaUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 验证码类型（支持算术、中文、GIF等）
    private static final int CAPTCHA_TYPE = Captcha.TYPE_DEFAULT;

    /**
     * 生成验证码图片
     * @param key 唯一标识（前端传递）
     */
    public void generateCaptcha(String key, HttpServletResponse response) {
        // 基础配置
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        log.info("生成验证码");
        try {
            // 创建验证码实例
            Captcha captcha;
            switch (CAPTCHA_TYPE) {
                case 1:
                    captcha = new ArithmeticCaptcha(150, 50);
                    break;
                case 2:
                    captcha = new ChineseCaptcha(150, 50);
                    break;
                case 3:
                    captcha = new ChineseGifCaptcha(150, 50);
                    break;
                default:
                    captcha = new SpecCaptcha(150, 50, 4);
                    break;
            }


            // 设置字体
            captcha.setFont(new Font("Verdana", Font.PLAIN, 32)); 
            
            // 生成验证码内容
            String code = captcha.text().toLowerCase();

            log.info("验证码内容：{}", code);

            // 存储到Redis（2分钟过期）
            redisTemplate.opsForValue().set(
                    CAPTCHA_PREFIX + key,
                code, 
                10,
                TimeUnit.MINUTES
            );

            // 输出图片流
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("生成验证码失败");
        }
    }

    /**
     * 验证码校验
     */
    public boolean validate(String key, String code) {
        String storedCode = redisTemplate.opsForValue().get(CAPTCHA_PREFIX + key);
        return code != null 
               && storedCode != null 
               && code.equalsIgnoreCase(storedCode);
    }
}